package huzh.foundation.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

/**
 *<p>title:ClassPathHacker</p>
 *<p>description:</p>
 * @since 2014-5-18
 * @author huzh
 * @version 1.0
 */
public class ClassPathHacker {
    /** cls*/
    @SuppressWarnings("unchecked")
    private static final Class[] cls = {URL.class };

    /**hackerPathList */
    private static ArrayList<String> hackerPathList = new ArrayList<String>();

    @SuppressWarnings("deprecation")
    private static void getClsIns(File paramFile)throws IOException{
        getClsIns(paramFile.toURL());
    }

    /**
     * @param paramURL
     * @throws IOException
     */
    private static void getClsIns(URL paramURL) throws IOException{
        URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<URLClassLoader> localClass = URLClassLoader.class;
        try{
            AccessibleObject oj = localClass.getDeclaredMethod("addURL", cls);
            oj.setAccessible(true);
           ((Method)oj).invoke(urlLoader, new Object[] { paramURL });
           
           return;
        }catch (Throwable e){
            e.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }
    }

    /**
     * @param paramString
     * @throws IOException
     */
    public static void addFile(String paramString) throws IOException{
        hackerPathList.add(paramString);
        File localFile = new File(paramString);
        getClsIns(localFile);
    }

    /**
     * @return
     */
    public static ArrayList<String> getHackerPathList(){
        return hackerPathList;
    }
}
